<?php
/**
 * @author VuNDH
 * @version 1.0
 * @created 29 May 2013
 */
class LikedController extends FController {
	/**
	 * This method is used to allow action
	 * @return string
	 */
	
	public function allowedActions()
	{
		return '*';
	}
	
	public function actionLiked(){
		$result			= array();
			
		if (currentUser() == false) {
			$result	= array (
				'error'		=> true,
				'message'	=> 'Please login!'
			);
		} else {
			if (!empty($_POST)) {
				$modelObject	= new Likes;
				
				
				$objectId		= $_POST['object_id'];
				$ratingType		= $_POST['rating_type'];
				$ratingValue	= $_POST['rating_value'];
				
				$find = $modelObject::model()->getLikeOfUser(currentUser()->id,$objectId);
				if(!empty($find)) $find->delete();
				
				$model = new Likes;
				$model->object_id = $objectId;
				$model->user_id = currentUser()->id;
				$model->created = time();
				if($model->save()){
					$statistic = $modelObject::model()->getLikes($model->object_id);
					$result	= array(
						'error'		=> false,
						'message'	=> 'This object has been updated.',
						'type'		=> 'like',
						'value'		=> 'Unlike',
						'people'	=> LikeString::outString(count($statistic), true),
						'number'=>count($statistic)
					);
				}else{
					$result	= array(
						'error'		=> true,
						'message'	=> 'This object has not been updated.',
					);
				}
				
			}
		}
		jsonOut($result);
	}
	public function actionLike(){
		$result			= array();
			
		if (currentUser() == false) {
			$result	= array (
				'error'		=> true,
				'message'	=> 'Please login!'
			);
		} else {
			if (!empty($_POST)) {

				$modelObject	= new Likes;
				$objectId		= $_POST['object_id'];
				$ratingType		= $_POST['rating_type'];
				$ratingValue	= $_POST['rating_value'];
				
				$find = $modelObject::model()->getLikeOfUser(currentUser()->id,$objectId);
				if(!empty($find)){
					if($find->delete()){
						$statistic = $modelObject::model()->getLikes($objectId);
						$update = count($statistic);
						$result	= array(
							'error'			=> false,
							'message'		=> 'This rate has been deleted',
							'classRating'	=> '',
							'type'			=> 'like',
							'value'			=> 'Like',
							'number'			=> $update,
							'people'		=> $update>0 ? '<a href="javascript:void(0)"> '.$update.' people </a> like this' : 'Like',
						);
					}else{
						$result	= array(
							'error'		=> true,
							'message'	=> 'This rate has not been deleted',
						);
					}
				}else{
					$result	= array(
						'error'		=> true,
						'message'	=> 'This rate has not been deleted',
					);
				}
				
				
				
			}
		}
		jsonOut($result);
	}
}